<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
/*
 * Include Zend mail library
 */
require_once dirname(__FILE__).'/../lib/Zend/Mime.php';
require_once dirname(__FILE__).'/../lib/Zend/Mime/Decode.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Storage/Abstract.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Protocol/Imap.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Storage/Writable/Interface.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Storage/Folder/Interface.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Storage/Folder.php';
require_once dirname(__FILE__).'/../lib/Zend/Mime/Decode.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Part/Interface.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Part.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Message/Interface.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Message.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Storage.php';
require_once dirname(__FILE__).'/../lib/Zend/Mail/Storage/Imap.php';

class ZemailGateway 
{
	/**
	 * Object Mail Storage
	 * @var Zend_Mail_Storage_Abstract
	 */
	public $emailGaterway = null;
	
	/**
	 * Help in make sender email (from) more Human-readable
	 * 
	 * @param string $from
	 * @return string sender email
	 */
	private function _fromDecoder($from)
	{
		$from = htmlentities($from);
		$from = explode("&lt;",$from);
		$patterns = array("<", ">", "&gt;", "&lt;");
		return trim(str_replace($patterns, '', $from[1]));
	}
	
	/**
	 * Help in make subject email more Human-readable
	 * 
	 * @param string $subject
	 * @return string subject email
	 */
	private function _subjectDecoder($subject){
		$subject = imap_mime_header_decode($subject);
		return $subject[0]->text;
	}
	
	/**
	 * Help in make recive email (to) more Human-readable
	 * 
	 * @param string $to
	 * @return string recive email
	 */
	private function _toDecoder($to){
		$to = htmlentities($to);
		$to = explode("&lt;",$to);
		$patterns = array("<", ">", "&gt;", "&lt;");
		if(sizeof($to)>1)
			return trim(str_replace($patterns, '', $to[1]));
		if(is_array($to))
			return $to[0];
		return $to;
	}
	
	/**
	 * Help in make sender name more Human-readable
	 * 
	 * @param string $from
	 * @return string sender name
	 */
	private function _nameDecoder($from){
		$from = imap_mime_header_decode($from);
		return $from[0]->text;
		
// 		$from = imap_mime_header_decode($from);
// 		$from = explode("&lt;",$from);
// 		$patterns = array("<", ">", "&gt;", "&lt;");
		
// 		return trim(str_replace($patterns, '', $from[0]));
	}
	
	private function _contentDecoder($part)
	{
		$content = $part->getContent();
		if($part->headerExists('content-transfer-encoding')){
			switch ($part->contentTransferEncoding) {
				case 'quoted-printable':
					$content = quoted_printable_decode($content);
				break;
				case 'base64':
					$content = base64_decode($content);
				break;
			}
		}
		return $content;
	}
	
	/**
	 * Connect Gateway
	 * 
	 * @param array $dataTestConnect date test conect gateway
	 * @return boolean true if this connect successfully, false otherwise
	 */
	function connectGateway($dataTestConnect = null)
	{	
		if($dataTestConnect) {
			$data = array(
				'host' => $dataTestConnect['host'],		// mail.phetbook.com
				'user' => $dataTestConnect['user'],		// gateway@phetbook.com
				'password' => $dataTestConnect['password'], // ?r*<r@q3nX*F
			);
			if ($dataTestConnect['ssl'] != 'None') {
				$data['ssl'] = $dataTestConnect['ssl'];
			}
			if (!empty($dataTestConnect['port'])) {
				$data['port'] = $dataTestConnect['port'];
			}
		} else {
			// it should get data from config
			$data = array(
					'host' => 'mail.phetbook.com',
					'user' => 'gateway@phetbook.com',
					'password' => '?r*<r@q3nX*F',
			);
		}
		
		try {
			$this->emailGaterway = new Zend_Mail_Storage_Imap($data);
			return true;
		} catch (Exception $e) {
			return false;
		}
	}
	
	/**
	 * Process retrive mail
	 */
	public function processRetriveMail()
	{
		$numsMessage = (int) $this->emailGaterway->countMessages();
		if ($numsMessage > 0) {
			echo $numsMessage . " messages found.<br />";

			$messageArr = array();
			for ($n = $numsMessage; $n > 0; $n--) {
				$message = $this->emailGaterway->getMessage($n);
				$from = $this->_fromDecoder($message->from);
				$date = date("Y-m-d h:i:s", strtotime($message->date)); 
				$subject = $this->_subjectDecoder($message->subject);
				$to  = $this->_toDecoder($message->envelopeTo);
				$senderName  = $this->_nameDecoder($message->from);
				$plainContent 		= null;
				$htmlContent  		= null;
				$file_attachment  	= '';
				$file_attachments  	= '';
				if ($message->isMultipart()) {
					$files  = array();
					foreach (new RecursiveIteratorIterator($message) as $part) {
						switch (strtok($part->contentType, ';')) {
							case 'text/plain':
								$plainContent = $this->_contentDecoder($part);
							break;
							case 'text/html':
								$htmlContent = $this->_contentDecoder($part);
							break;
							default: //attachment handle
								$file_attachment = $part->getHeader('content-disposition');
	                                $file_attachment = explode("=",$file_attachment);
	                                $file_attachment = str_replace('"',"",$file_attachment[1]);
								// upload the attachment
								$content = $this->_contentDecoder($part); // get content
								$path = _PS_MODULE_DIR_ . 'zhelpdesk' . DS . 'fileattach' . DS . $file_attachment;
								$fh = fopen($path, 'w');
								fwrite($fh, $content);
								fclose($fh);
								//multi file attachment
								$files[] = $file_attachment;
							break;
						}
					}
					$file_attachments = implode(';', $files);
				} else {
					$plainContent = $this->_contentDecoder($message);
				}
				
				$messageArr[] =  array('from' => $from,
									 'date' => $date,
									 'subject' => $subject,
									 'to' => $to,
									 'senderName' => $senderName,
									 'content'=> $plainContent,
									 'file_attachment'=>$file_attachments);
			}
		// delete mail
			for ($i = count($this->emailGaterway); $i; --$i) {
	    		$this->emailGaterway->removeMessage($i);
			}
			return $messageArr;
		}
	}
}		


